<script lang="ts" setup>
import type { Category } from '../data'
import { ElDialog, ElForm, ElFormItem, ElInput, ElSelectV2, FormInstance, FormRules } from 'element-plus'
import { useCategoriesStore } from '../store'
import { computed, reactive, ref } from 'vue'

const categories = useCategoriesStore()

const title = computed(() => (categories.form.id ? '新增分类' : '更新分类'))

const options = computed(() =>
  categories.form.allTags.map(({ id, name }) => ({
    label: name,
    value: id,
  }))
)

const rules = reactive<FormRules<Pick<Category, 'name' | 'description' | 'tagIdList'>>>({
  tagIdList: [{ required: true, trigger: 'blur', message: '标签不能为空' }],
  name: [{ required: true, trigger: 'blur', message: '分类名称不能为空', whitespace: false }],
  description: [{ required: false, whitespace: false }],
})

const formRef = ref<FormInstance>()

const onClickSubmitForm = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) categories.onSubmitPut()
  })
}

const onClickResetForm = () => {
  formRef.value?.resetFields
  categories.onResetForm()
}
</script>

<template>
  <ElDialog v-model="categories.form.on" :title @close="categories.onResetForm">
    <ElForm ref="formRef" :model="categories.form.items" :rules label-width="auto">
      <ElFormItem label="所属标签" required prop="tagIdList">
        <ElSelectV2 v-model="categories.form.items.tagIdList" :options multiple placeholder="请选择分类" />
      </ElFormItem>
      <ElFormItem label="分类名称" required prop="name">
        <ElInput v-model="categories.form.items.name" />
      </ElFormItem>
      <ElFormItem label="分类描述" prop="description">
        <ElInput v-model="categories.form.items.description" type="textarea" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="onClickResetForm">取消</ElButton>
      <ElButton type="primary" @click="onClickSubmitForm">确定</ElButton>
    </template>
  </ElDialog>
</template>
